<template>
  <view class="weather-card">
    <!-- 天气卡片内容 -->
    <view v-if="weatherLoaded" class="weather-container weather-loaded">
      <!-- 头部区域 -->
      <view class="weather-header">
        <view class="header-left">
          <span class="weather-tag">天气预报</span>
          <view class="location-info" @click="chooseCity">
            <u-icon name="map-marker" size="26" color="#409eff"></u-icon>
            <text class="location-text">{{ currentWeather.city }} {{ currentWeather.district }}</text>
            <u-icon name="arrow-right" size="20" color="#999" class="location-arrow"></u-icon>
          </view>
        </view>
        <view class="header-right">
          <view class="update-time">
            <text>更新于 {{ currentWeather.updateTime }}</text>
          </view>
          <!-- 刷新图标 -->
          <u-icon 
            name="reload" 
            size="28" 
            color="#409eff" 
            class="refresh-icon"
            @click="refreshWeather"
            :class="{ 'refreshing': isRefreshing }"
          ></u-icon>
        </view>
      </view>

      <!-- 实时天气主体 -->
      <view class="current-weather">
        <view class="current-main">
          <view class="temp-container">
            <text class="current-temp">{{ currentWeather.temperature }}°</text>
            <text class="temp-unit">C</text>
          </view>
          <view class="weather-status">
            <text class="weather-text">{{ currentWeather.weather }}</text>
            <view class="weather-icon">
              <image :src="getWeatherIcon(currentWeather.weather)" mode="widthFix"></image>
            </view>
          </view>
        </view>
        
        <!-- 天气详情指标 -->
        <view class="weather-metrics">
          <view class="metric-item">
            <text class="metric-value">{{ currentWeather.windDirection }}</text>
            <text class="metric-label">风向</text><image class="forecast-icon" src="/static/images/fx.png">
          </view>
          <view class="metric-item">
            <text class="metric-value">{{ currentWeather.windPower }}</text>
            <text class="metric-label">风力</text>
			<image class="forecast-icon" src="/static/images/fl.png">
          </view>
          <view class="metric-item">
            <text class="metric-value">{{ currentWeather.humidity }}%</text>
            <text class="metric-label">湿度</text>
			<image class="forecast-icon" src="/static/images/sd.png">
          </view>
        </view>
      </view>

      <!-- 未来预报 -->
      <view class="forecast-section">
        <text class="section-title">未来预报</text>
        <view class="forecast-slider">
          <view class="forecast-item" v-for="(day, index) in futureForecast" :key="index" :class="{ 'today': index === 0 }">
            <text class="forecast-date">{{ formatDate(day.date) }}</text>
            <text class="forecast-week">{{ day.week }}</text>
            <image :src="getWeatherIcon(day.day.weather)" mode="widthFix" class="forecast-icon"></image>
            <text class="forecast-weather">{{ day.day.weather }}</text>
            <text class="forecast-temp">{{ day.day.temperature }}°</text>
          </view>
        </view>
      </view>
    </view>

    <!-- 定位状态 -->
    <view class="loading-state" v-else-if="isLocating">
      <u-icon name="location" color="#409eff" size="48" class="loading-spinner"></u-icon>
      <text class="loading-text">正在获取您的位置...</text>
    </view>

    <!-- 加载状态 -->
    <view class="loading-state" v-else-if="loading || isRefreshing">
      <u-icon name="loading" color="#409eff" size="48" class="loading-spinner"></u-icon>
      <text class="loading-text">{{ isRefreshing ? '刷新中...' : '获取天气信息中...' }}</text>
    </view>

    <!-- 错误状态 -->
    <view class="error-state" v-else>
      <u-icon name="cloud-off" color="#f56c6c" size="48"></u-icon>
      <text class="error-text">{{ errorMsg || '获取天气失败' }}</text>
      <button @click="initWeather()" class="retry-btn">
        <u-icon name="refresh" size="24" color="#fff"></u-icon>
        <text>重新加载</text>
      </button>
    </view>
    
    <u-toast ref="uToast" />
  </view>
</template>

<script>
export default {
  props: {
    // 允许页面传入API密钥
    apiKey: {
      type: String,
      required: true
    },
    // 允许页面传入默认城市adcode
    defaultAdcode: {
      type: String,
      default: '320300'
    }
  },
  data() {
    return {
      // 天气数据
      currentWeather: {
        city: '加载中',
        district: '',
        temperature: '--',
        weather: '',
        windDirection: '--',
        windPower: '--',
        humidity: '--',
        updateTime: ''
      },
      futureForecast: [],
      // 状态变量
      loading: false,
      weatherLoaded: false,
      errorMsg: '',
      isLocating: false, // 定位状态
      isRefreshing: false // 刷新状态
    };
  },
  methods: {
    /**
     * 组件初始化方法，供页面调用
     * 页面可以在需要的时候调用此方法初始化或重新加载天气数据
     */
    initWeather() {
      // 重置状态
      this.errorMsg = '';
      this.weatherLoaded = false;
      
      // 开始定位并获取天气
      this.getUserLocation();
    },
    
    /**
     * 刷新天气数据（只刷新天气，不重新定位）
     */
    refreshWeather() {
      if (this.isRefreshing) return;
      
      this.isRefreshing = true;
      this.$refs.uToast.show({
        title: '正在刷新...',
        duration: 800
      });
      
      this.getWeatherData().then(() => {
        this.isRefreshing = false;
        this.$refs.uToast.show({
          title: '刷新成功',
          duration: 1000
        });
      }).catch(() => {
        this.isRefreshing = false;
        this.$refs.uToast.show({
          title: '刷新失败',
          duration: 1000,
          type: 'error'
        });
      });
    },
    
    /**
     * 获取用户位置（经纬度）
     */
    getUserLocation() {
      this.isLocating = true;
      
      // 使用uni-app的定位API获取经纬度
      uni.getLocation({
        type: 'gcj02', // 腾讯地图使用gcj02坐标系
        geocode: false,
        success: (res) => {
          this.isLocating = false;
          // 调用逆地址解析获取adcode
          this.getAdcodeByLocation(res.longitude, res.latitude);
        },
        fail: (err) => {
          this.isLocating = false;
          console.error('获取位置失败：', err);
          
          // 根据错误码给出具体提示
          let errMsg = '获取位置失败，请允许定位权限';
          if (err.errCode === 1) {
            errMsg = '请在设置中开启位置权限';
          } else if (err.errCode === 2) {
            errMsg = '位置服务不可用，请检查设备设置';
          } else if (err.errCode === 3) {
            errMsg = '定位超时，请稍后重试';
          }
          
          this.errorMsg = errMsg;
          
          // 定位失败时使用默认城市
          setTimeout(() => {
            this.getWeatherData();
          }, 1500);
        }
      });
    },
    
    /**
     * 通过经纬度获取行政区划代码（adcode）
     */
    getAdcodeByLocation(lng, lat) {
      this.loading = true;
      
      uni.request({
        url: 'https://apis.map.qq.com/ws/geocoder/v1/',
        method: 'GET',
        data: {
          key: this.apiKey,
          location: `${lat},${lng}`, // 纬度在前，经度在后
          get_poi: 0
        },
        success: (res) => {
          if (res.data.status === 0 && res.data.result.ad_info) {
            // 获取到adcode后更新并获取天气
            this.adcode = res.data.result.ad_info.adcode;
            this.getWeatherData();
          } else {
            this.loading = false;
            this.errorMsg = '解析位置信息失败，使用默认城市';
            // 解析失败使用默认城市
            setTimeout(() => {
              this.getWeatherData();
            }, 1500);
          }
        },
        fail: (err) => {
          this.loading = false;
          this.errorMsg = '位置解析请求失败，使用默认城市';
          console.error('解析位置失败：', err);
          // 请求失败使用默认城市
          setTimeout(() => {
            this.getWeatherData();
          }, 1500);
        }
      });
    },
    
    /**
     * 获取天气数据（实时+未来预报）
     */
    getWeatherData() {
      return new Promise((resolve, reject) => {
        this.loading = true;
        this.weatherLoaded = false;
        
        // 1. 获取实时天气
        uni.request({
          url: 'https://apis.map.qq.com/ws/weather/v1/',
          method: 'GET',
          data: {
            key: this.apiKey,
            adcode: this.adcode || this.defaultAdcode,
            type: 'now' // 实时天气
          },
          timeout: 10000, // 10秒超时
          success: (res) => {
            const realtimeData = res.data;
            if (realtimeData.status === 0 && realtimeData.result.realtime) {
              const realtime = realtimeData.result.realtime[0];
              // 处理实时天气数据
              this.currentWeather = {
                province: realtime.province,
                city: realtime.city,
                district: realtime.district,
                weather: realtime.infos.weather,
                temperature: realtime.infos.temperature,
                windDirection: realtime.infos.wind_direction,
                windPower: realtime.infos.wind_power,
                humidity: realtime.infos.humidity,
                updateTime: this.formatTime(realtime.update_time)
              };
              
              // 2. 获取未来预报
              this.getFutureWeather(resolve, reject);
            } else {
              this.errorMsg = realtimeData.message || '获取实时天气失败';
              this.loading = false;
              this.weatherLoaded = false;
              reject();
            }
          },
          fail: (err) => {
            this.errorMsg = '网络请求失败，请检查网络';
            this.loading = false;
            this.weatherLoaded = false;
            console.error('实时天气请求失败：', err);
            reject();
          }
        });
      });
    },
    
    /**
     * 获取未来天气预报
     */
    getFutureWeather(resolve, reject) {
      uni.request({
        url: 'https://apis.map.qq.com/ws/weather/v1/',
        method: 'GET',
        data: {
          key: this.apiKey,
          adcode: this.adcode || this.defaultAdcode,
          type: 'future', // 未来预报
          get_md: 0 // 当天+未来3天
        },
        timeout: 10000, // 10秒超时
        success: (res) => {
          const futureData = res.data;
          if (futureData.status === 0 && futureData.result.forecast) {
            this.futureForecast = futureData.result.forecast[0].infos;
            this.weatherLoaded = true;
            resolve();
          } else {
            this.errorMsg = futureData.message || '获取未来天气失败';
            reject();
          }
          this.loading = false;
        },
        fail: (err) => {
          this.errorMsg = '未来天气预报请求失败';
          this.loading = false;
          console.error('未来天气请求失败：', err);
          reject();
        }
      });
    },
    
    /**
     * 根据天气状态获取对应图标
     */
    getWeatherIcon(weather) {
      const weatherMap = {
        '晴': '/static/images/qt.png',
        '多云': '/static/images/dy.png',
        '阴': '/static/images/yt.png',
        '阵雨': '/static/images/zy.png',
        '雷阵雨': '/static/images/lzy.png',
        '小雨': '/static/images/xy.png',
        '中雨': '/static/images/zhongyu.png',
        '大雨': '/static/images/dayu.png',
        '暴雨': '/static/images/baoyu.png',
        '雪': '/static/images/xue.png',
        '雾': '/static/images/wu.png',
        '霾': '/static/images/mai.png'
      };
      return weatherMap[weather] || '/static/images/qt.png';
    },
    
    /**
     * 格式化时间
     */
    formatTime(timeStr) {
      if (!timeStr) return '';
      return timeStr.split(' ')[1].slice(0, 5);
    },
    
    /**
     * 格式化日期
     */
    formatDate(dateStr) {
      if (!dateStr) return '';
      return dateStr.split('-').slice(1).join('-');
    },
    
    /**
     * 城市选择功能
     */
    chooseCity() {
      // this.$refs.uToast.show({
      //   title: '城市选择功能待开发'
      // });
    }
  }
};
</script>

<style lang="scss">
/* 样式与之前版本保持一致 */
.weather-card {
  width: 92%;
  margin: 24rpx auto;
  border-radius: 24rpx;
  overflow: hidden;
}

.weather-container {
  background: linear-gradient(135deg, #f5f7fa 0%, #eef1f5 100%);
  border-radius: 24rpx;
  box-shadow: 0 10rpx 30rpx rgba(0, 0, 0, 0.08);
  padding: 28rpx;
  opacity: 0;
  transform: translateY(20rpx);
  transition: all 0.5s cubic-bezier(0.4, 0, 0.2, 1);
  box-sizing: border-box;
}

.weather-loaded {
  opacity: 1;
  transform: translateY(0);
}

.weather-header {
  display: flex;
  justify-content: space-between;
  align-items: flex-start;
  margin-bottom: 30rpx;
}

.header-left {
  display: flex;
  flex-direction: column;
  gap: 10rpx;
}

.header-right {
  display: flex;
  flex-direction: column;
  align-items: flex-end;
  gap: 8rpx;
}

.weather-tag {
  display: inline-block;
  padding: 6rpx 16rpx;
  background: linear-gradient(90deg, #409eff 0%, #69b1ff 100%);
  color: white;
  font-size: 30rpx;
  border-radius: 20rpx;
  box-shadow: 0 4rpx 12rpx rgba(64, 158, 255, 0.3);
}

.location-info {
  display: flex;
  align-items: center;
  gap: 10rpx;
  padding: 8rpx 0;
  cursor: pointer;
}

.location-text {
  font-size: 28rpx;
  color: #303133;
  font-weight: 500;
}

.location-arrow {
  opacity: 0.7;
  transition: transform 0.3s;
}

.location-info:hover .location-arrow {
  transform: translateX(5rpx);
}

.update-time {
  font-size: 22rpx;
  color: #909399;
  padding-top: 12rpx;
}

.refresh-icon {
  cursor: pointer;
  transition: transform 0.3s ease;
  margin-top: 5rpx;
}

.refresh-icon:hover {
  transform: rotate(30deg);
}

.refreshing {
  animation: spin 1s linear infinite;
}

.current-weather {
  display: flex;
  flex-direction: column;
  gap: 30rpx;
  margin-bottom: 20rpx;
}

.current-main {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 10rpx 0;
}

.temp-container {
  display: flex;
  align-items: baseline;
  gap: 10rpx;
}

.current-temp {
  font-size: 80rpx;
  font-weight: 700;
  color: #303133;
  line-height: 1;
  background: linear-gradient(90deg, #303133 0%, #606266 100%);
  -webkit-background-clip: text;
  background-clip: text;
  color: transparent;
}

.temp-unit {
  font-size: 32rpx;
  color: #606266;
  margin-bottom: 10rpx;
}

.weather-status {
  display: flex;
  align-items: center;
  gap: 20rpx;
}

.weather-text {
  font-size: 36rpx;
  color: #303133;
  font-weight: 500;
}

.weather-icon image {
  width: 100rpx;
  height: 100rpx;
  filter: drop-shadow(0 5rpx 10rpx rgba(0, 0, 0, 0.1));
}

.weather-metrics {
  display: flex;
  justify-content: space-around;
  padding: 20rpx 0;
  background: rgba(255, 255, 255, 0.7);
  border-radius: 16rpx;
  backdrop-filter: blur(10rpx);
  box-shadow: 0 4rpx 12rpx rgba(0, 0, 0, 0.05);
}

.metric-item {
  display: flex;
  flex-direction: column;
  align-items: center;
  gap: 8rpx;
  padding: 0 10rpx;
}

.metric-value {
  font-size: 28rpx;
  color: #303133;
  font-weight: 500;
}

.metric-label {
  font-size: 26rpx;
  color: #909399;
}

.forecast-section {
  margin-top: 10rpx;
}

.section-title {
  display: block;
  font-size: 28rpx;
  color: #606266;
  margin-bottom: 20rpx;
  padding-left: 8rpx;
  font-weight: 500;
}

.forecast-slider {
  display: flex;
  gap: 16rpx;
  overflow-x: auto;
  padding-bottom: 10rpx;
  scrollbar-width: none;
  &::-webkit-scrollbar {
    display: none;
  }
}

.forecast-item {
  display: flex;
  flex-direction: column;
  align-items: center;
  min-width: 140rpx;
  padding: 20rpx 10rpx;
  background: rgba(255, 255, 255, 0.6);
  border-radius: 16rpx;
  backdrop-filter: blur(8rpx);
  box-shadow: 0 4rpx 12rpx rgba(0, 0, 0, 0.05);
  transition: transform 0.3s, box-shadow 0.3s;
}

.forecast-item:hover {
  transform: translateY(-5rpx);
  box-shadow: 0 8rpx 20rpx rgba(0, 0, 0, 0.08);
}

.forecast-item.today {
  background: linear-gradient(135deg, #e6f7ff 0%, #d1ecf1 100%);
  border: 1rpx solid #b3e0ff;
}

.forecast-date {
  font-size: 28rpx;
  color: #303133;
  font-weight: 500;
  margin-bottom: 6rpx;
}

.forecast-week {
  font-size: 26rpx;
  color: #909399;
  margin-bottom: 15rpx;
}

.forecast-icon {
  width: 60rpx;
  height: 60rpx;
  margin-bottom: 15rpx;
}

.forecast-weather {
  font-size: 30rpx;
  color: #303133;
  margin-bottom: 10rpx;
  text-align: center;
  min-height: 30rpx;
}

.forecast-temp {
  font-size: 28rpx;
  color: #409eff;
  font-weight: 500;
}

.loading-state {
  display: flex;
  flex-direction: column;
  align-items: center;
  padding: 80rpx 0;
  background: white;
  border-radius: 24rpx;
  box-shadow: 0 10rpx 30rpx rgba(0, 0, 0, 0.05);
}

.loading-spinner {
  animation: spin 1.5s linear infinite;
}

.loading-text {
  margin-top: 20rpx;
  font-size: 28rpx;
  color: #606266;
}

.error-state {
  display: flex;
  flex-direction: column;
  align-items: center;
  padding: 60rpx 30rpx;
  background: white;
  border-radius: 24rpx;
  box-shadow: 0 10rpx 30rpx rgba(0, 0, 0, 0.05);
  text-align: center;
}

.error-text {
  margin: 20rpx 0;
  font-size: 28rpx;
  color: #f56c6c;
  max-width: 80%;
}

.retry-btn {
  display: flex;
  align-items: center;
  gap: 10rpx;
  padding: 14rpx 30rpx;
  background: linear-gradient(90deg, #409eff 0%, #69b1ff 100%);
  color: white;
  font-size: 28rpx;
  border-radius: 30rpx;
  box-shadow: 0 4rpx 12rpx rgba(64, 158, 255, 0.3);
  border: none;
  margin-top: 10rpx;
  transition: transform 0.2s;
}

.retry-btn:active {
  transform: scale(0.95);
}

@keyframes spin {
  from { transform: rotate(0deg); }
  to { transform: rotate(360deg); }
}
</style>
